<script lang="ts" setup>
import { useStore } from "@/stores/user";
import API from "@/service/api/useinfo";
import { request } from "@/service/request";
import { reactive, ref, watch, onActivated } from "vue";
import { mStyles } from "@/utils/useStyles";
import { useRouter, useRoute } from "vue-router";
import { someFieldStore } from '@/stores/somefield';
import { getUrlParamValue } from "@/utils/getUrlParams";

const props = defineProps({
    iTemplateId: {
        type: Number,
        default: ''
    },
    iWorkCode: {
        type: String,
        default: ''
    }
})

interface UseInfo {
    game_name: string;
    game_id: string | number;
    role_id: string | number;
    role_name: string;
    server_name: string;
    work_order_template_id: number;
}

interface ClientField {
    key: keyof UseInfo;
    value: string | number;
}

//UID
const mStore = useStore();
const mSomeField = someFieldStore();

// 标志变量，用于区分URL参数填充和正常交互
let isUrlParamsLoaded = false;

//账号信息
const mUseInfo = reactive<UseInfo>({
    'game_name': '',
    'game_id': 0,
    'role_id': '',
    'role_name': '',
    'server_name': '',
    'work_order_template_id': 0
})


mUseInfo.work_order_template_id = props.iTemplateId


const mList: any = reactive({
    gameList: {},
    serverList: {},
    roleList: {},
})

const mGameServer = ref(false);
const mGameRolename = ref(false);
// 添加状态变量来记录数据情况
const mServerStatus = ref('normal'); // 'empty', 'single', 'normal'
const mRoleStatus = ref('normal');   // 'empty', 'single', 'normal'

const clkList = async () => {
    mList.gameList = await request.post<any>(API.gameList) as any;
    //默认选中第一个
    if (mList.gameList.data.length > 0 && mUseInfo.game_id == '') {
        mUseInfo.game_id = mList.gameList.data[0].game_id;
        mUseInfo.game_name = mList.gameList.data[0].game_name;
    }

    //没有数据不选择
    if (!mList.gameList.data.length || mList.gameList.data.length == 1 || getUrlParamValue('access_token', mSomeField.clientfields) != null) {
        mClient.value = true;
    } else {
        mClient.value = false;
    }
}

onActivated(async () => {
    // 先清空数据
    mUseInfo.game_name = '';
    mUseInfo.game_id = 0;
    mUseInfo.role_id = '';
    mUseInfo.role_name = '';
    mUseInfo.server_name = '';
    
    // 只有在非客户端模式下才重新加载数据
    if (getUrlParamValue('access_token', mSomeField.clientfields) == null) {
        // 总是请求游戏列表，确保有数据
        await clkList();
    }
})

const clkGetServerList = async () => {
    mList.serverList = await request.post<any>(API.serverList, { game_id: mUseInfo.game_id }) as any;
    //默认选中第一个
    if (mList.serverList.data.length > 0 && mUseInfo.server_name == '') {
        mUseInfo.server_name = mList.serverList.data[0].server_name;
    }

    // 更新状态和提示类型
    if (!mList.serverList.data.length) {
        mGameServer.value = true;
        mServerStatus.value = 'empty';
    } else if (mList.serverList.data.length == 1) {
        mGameServer.value = true;
        mServerStatus.value = 'single';
    } else {
        mGameServer.value = false;
        mServerStatus.value = 'normal';
    }
}

const clkGetRoleList = async () => {
    mList.roleList = await request.post<any>(API.roleList, { game_id: mUseInfo.game_id }) as any;
    //默认选中第一个
    if (mList.roleList.data.length > 0 && mUseInfo.role_id == '') {
        mUseInfo.role_id = mList.roleList.data[0].role_id;
        mUseInfo.role_name = mList.roleList.data[0].role_name;
    }

    // 更新状态和提示类型
    if (!mList.roleList.data.length) {
        mGameRolename.value = true;
        mRoleStatus.value = 'empty';
    } else if (mList.roleList.data.length == 1) {
        mGameRolename.value = true;
        mRoleStatus.value = 'single';
    } else {
        mGameRolename.value = false;
        mRoleStatus.value = 'normal';
    }
}

//如果有url参数就填充
if (mSomeField.clientfields && Array.isArray(mSomeField.clientfields)) {
    (mSomeField.clientfields as ClientField[]).forEach((field) => {
        if (mUseInfo.hasOwnProperty(field.key)) {
            // 如果field.value是null则不赋值
            if (field.value === 'null' || field.value === null) {
                return; // 跳过当前字段处理
            }
            // 根据目标属性类型进行值转换
            const targetType = typeof mUseInfo[field.key];
            switch (targetType) {
                case 'number':
                    (mUseInfo as any)[field.key] = Number(field.value) || mUseInfo[field.key];
                    break;
                default:
                    (mUseInfo as any)[field.key] = field.value.toString();
            }

        }
    });
    
    // 设置标志，表示已加载URL参数
    isUrlParamsLoaded = true;

    // 不在此处主动拉取，交由 watch(game_id) 统一触发
}

watch(
    () => mUseInfo.game_id,
    (newGameId) => {
        if (newGameId) {
            mUseInfo.game_id = Number(mUseInfo.game_id);
            
            // 重要：只有在不是URL参数加载的情况下才清空其他字段
            // 这样可以保留通过URL填充的role_id, role_name, server_name
            if (!isUrlParamsLoaded) {
                mUseInfo.role_id = '';
                mUseInfo.role_name = '';
                mUseInfo.server_name = '';
            }
            
            // 无论何种情况都调用接口以确保数据完整
            clkGetServerList();
            clkGetRoleList();
            
            // 重置标志，确保后续的game_id变化正常处理
            isUrlParamsLoaded = false;
        }
    },
    { immediate: true }
);

//账号信息选择
const mShowPicker = ref(false);
const mPickerList = ref();
const mPickerValue = ref();
const clkOnConfirm = (selectedOptions: any) => {
    mShowPicker.value = !mShowPicker;
    let res = selectedOptions.selectedOptions[0];
    switch (mCustomFieldName.value.text) {
        case 'game_name':
            mUseInfo.game_id = res.game_id
            mUseInfo.game_name = res.game_name
            break;
        case 'server_name':
            mUseInfo.server_name = res.server_name
            break;
        default:
            mUseInfo.role_id = res.role_id
            mUseInfo.role_name = res.role_name
            break;
    }
}

//自定义下拉选择字段
const mCustomFieldName = ref({
    text: 'game_name',
    value: 'game_id',
});

const clkChoose = (e: any, field?: [string, string] | undefined) => {
    //选中
    switch (e) {
        case 'gameList':
            mPickerValue.value = [mUseInfo.game_id];
            break;
        case 'serverList':
            mPickerValue.value = [mUseInfo.server_name];
            break;
        case 'roleList':
            mPickerValue.value = [mUseInfo.role_id];
            break;
    }

    mShowPicker.value = true;
    mPickerList.value = mList[e].data;

    if (field) {
        mCustomFieldName.value.text = field[0];
        mCustomFieldName.value.value = field[1];
    } else {
        mCustomFieldName.value.text = 'game_name';
        mCustomFieldName.value.value = 'game_id';
    }
}

//提交问题
let mRouter = useRouter();
let mRoute = useRoute();

const clkQuestion = () => {
    if (mIsConfirmDisabled.value) return;
    mRouter.push({
        path: '/question',
        query: mUseInfo,
    });
};

const mClient = ref(false);

// 添加条件判断，只在非客户端模式时调用一次
if (getUrlParamValue('access_token', mSomeField.clientfields) == null) {
    clkList();
}

if (getUrlParamValue('access_token', mSomeField.clientfields) != null) {
    mClient.value = true;
}

//确认按钮css
const mConfirmButton = ref('w-[330px]');

if (getUrlParamValue('access_token', mSomeField.clientfields) != null || getUrlParamValue('access_token', mSomeField.clientfields) == '') {
    mConfirmButton.value = 'w-[100%]'
} else {
    mConfirmButton.value = 'w-[330px]'
}

//大陆认证
const mDluShow = ref(true);
if (props.iWorkCode == 'shenfenrenzheng') {
    mDluShow.value = false;
}else{
    mDluShow.value = true;
}

// 添加确认按钮禁用状态变量
const mIsConfirmDisabled = ref(false);

// 监听role_id、role_name和server_name的变化，控制确认按钮的禁用状态
watch(
    () => [mUseInfo.role_id, mUseInfo.role_name, mUseInfo.server_name, mDluShow.value],
    ([roleId, roleName, serverName, dluShow]) => {
        if (props.iWorkCode == 'find_account') {
            mIsConfirmDisabled.value = false; // find_account时不设置禁用状态
        } else if (!dluShow) {
            mIsConfirmDisabled.value = false; // 认证不显示时按钮可用
        } else {
            mIsConfirmDisabled.value = !(roleId && roleName && serverName);
        }
    },
    { immediate: true }
);
// 区服角色选择提示 - 修改为接受类型参数并显示不同提示
const mTips = (type: 'server' | 'role') => {
    if (type === 'server') {
        if (mServerStatus.value === 'empty') {
            showToast({ message: "没有区服信息" });
        } else if (mServerStatus.value === 'single') {
            showToast({ message: "只有一条区服信息，已自动选择" });
        }
    } else if (type === 'role') {
        if (mRoleStatus.value === 'empty') {
            showToast({ message: "没有角色信息" });
        } else if (mRoleStatus.value === 'single') {
            showToast({ message: "只有一条角色信息，已自动选择" });
        }
    }
}

const game_icon = ref('arrow-down');
//客户端不显示游戏选择icon
const client_game = () =>{
    if(mClient.value){
        game_icon.value = ''
    }else{
        game_icon.value = 'arrow-down'
    }
}
client_game();
</script>

<template>
    <div class="gr-verify">
        <h1 class="text-[34px] font-normal m-b-[40px]">请核实你的信息</h1>
        <cVanfield readonly label="账号信息：" v-model="mStore.token.user_name" class="m-b-[20px] rounded-[12px]" 
            label-width="auto"></cVanfield>
        <cVanfield readonly name="picker" placeholder="请选择游戏" class="text-[30px] m-b-[20px] rounded-[12px]" 
            v-on="mClient ? {} : { click: () => clkChoose('gameList') }" v-model="mUseInfo.game_name" 
            :right-icon="game_icon" :disabled="mClient">
        </cVanfield>
        <cVanfield readonly name="picker" placeholder="请选择区服" v-model="mUseInfo.server_name" v-show="mDluShow" 
            class="rounded-[12px] m-b-[20px] clickable-field" 
            v-on="mGameServer ? { click: () => mTips('server') } : { click: () => clkChoose('serverList', ['server_name', 'server_name']) }" 
            right-icon="arrow-down" :disabled="mGameServer">
        </cVanfield>
        <cVanfield readonly name="picker" placeholder="请选择角色" v-model="mUseInfo.role_name" v-show="mDluShow" 
            class="rounded-[12px] clickable-field" 
            v-on="mGameRolename ? { click: () => mTips('role') } : { click: () => clkChoose('roleList', ['role_name', 'role_id']) }" 
            right-icon="arrow-down" :disabled="mGameRolename">
        </cVanfield>
        <div class="gr-operate m-t-[40px]">
            <cButton round :iColor="mStyles.color1" iHeight="9vmin" class="w-[300px]" hairline iFontSize="3vmin" 
                v-show="getUrlParamValue('access_token', mSomeField.clientfields) == null" 
                @click="mRouter.push({ path: '/login', query: { redirect: mRoute.fullPath } })">
                登录其他账号
            </cButton>
            <cButton round :iColor="mStyles.color10" iHeight="9vmin" iLinearGradien :iBgColor="mStyles.bgcolor" 
                :class="mConfirmButton" iFontSize="3vmin" @click="clkQuestion" :disabled="mIsConfirmDisabled">
                确认
            </cButton>
        </div>
    </div>
    <van-popup v-model:show="mShowPicker" destroy-on-close position="bottom">
        <van-picker :columns="mPickerList" :model-value="mPickerValue" @confirm="clkOnConfirm" 
            :columns-field-names="mCustomFieldName" @cancel="mShowPicker = false" />
    </van-popup>
</template>

<style lang="scss" scoped>
.gr-verify {
    margin: 10px;
    border-radius: 5px;

    :deep(.van-cell:after) {
        border: none;
    }

    h1 {
        font-size: 34px;
        padding: 0;
        color: #3D3D3D;
        text-align: center;
        font-weight: 500;
    }

    .gr-operate {
        display: flex;
        padding: 0 20px;
        justify-content: space-between;
    }
}

:deep(.van-picker__confirm) {
    color: $color1;
}

:deep(.van-field__label) {
    margin-right: 0;
}

:deep(.van-cell) {
    font-size: 30px;
    font-weight: 400;
}

:deep(.van-field__value) {
    font-size: 30px;
    font-weight: 400;
}

:deep(.van-haptics-feedback) {
    font-size: 30px;
    font-weight: 400;
}

:deep(.van-ellipsis) {
    font-size: 30px;
    font-weight: 400;
}

/* 解决禁用状态下点击区域小的问题 */
.clickable-field {
    position: relative;
    cursor: pointer;
}

.clickable-field:deep(.van-field--disabled) {
    pointer-events: none;
    /* 禁用原始元素的点击事件 */
}

.clickable-field::after {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    z-index: 1;
    pointer-events: auto;
}

/* 确保禁用状态下的文本颜色和背景色保持不变 */
.clickable-field:deep(.van-field--disabled .van-field__value) {
    color: #969799;
}

.clickable-field:deep(.van-field--disabled .van-field__placeholder) {
    color: #C8C9CC;
}
</style>